import sun.java2d.marlin.DPathConsumer2D;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端解决首发消息的冲突问题
 * 由于客户端start方法中循环进行的操作顺序是先输入一句话后将其发送给服务端，然后再读取服务端发送回来的
 * 一句话。这导致如果客户端不输入内容就无法收到服务端发送过来的消息(其他客户端的聊天内容)。因此要将客户端中接受
 * 消息的工作移动到一个单独的线程上执行，才能保证首发消息互不打扰
 */

public class Client {
    private Socket socket;
    Scanner scan = new Scanner(System.in);

    /**
     * 构造器,初始化客户端
     */
    public Client() {
        try {
            System.out.println("正在启动客户端...");
            socket = new Socket("localhost", 8088);
            System.out.println("客户端已连接到服务端!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户端开始工作的方法
     */
    public void start() {

        try {
            ServerHandler handler = new ServerHandler(socket);
            Thread t = new Thread(handler);
            t.setDaemon(true);
            t.start();

            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);
            String str = null;
            while (true) {
                str = scan.nextLine();
                if ("exit".equalsIgnoreCase(str)) {
                    break;
                }
                pw.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}

class ServerHandler implements Runnable {
    private Socket socket;

    public ServerHandler(Socket socket){
        this.socket = socket;
    }

    public void run(){
        try {
            InputStream in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String s;
            while ((s=br.readLine())!=null){
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
